package com.kinptm.masterclock.utils;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

import com.kinptm.masterclock.Intents;
import com.kinptm.masterclock.MasterClockApplication;
import com.kinptm.masterclock.bean.AlarmClock;
import com.kinptm.masterclock.bean.TimerRecord;
import com.kinptm.masterclock.db.DbHelper;

import org.joda.time.DateTime;
import org.joda.time.Period;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by pc on 13-11-15.
 */
public class AlarmUtil {

    /**
     * 设置闹钟
     *
     * @param clock 需要设置的闹钟
     */
    public static void plan2AlarmClock(AlarmClock clock) {
        planAlarm(Intents.ALARM.ACTION_CLOCK_RECEIVER, clock.getId(), clock.getAlarmMillis());

        Ln.d("设置闹钟时间 %s ", new DateTime(clock.getAlarmMillis()).toString("yyyy-MM-dd HH:mm:ss"));
    }

    public static void cancel2AlarmClock(AlarmClock clock) {
        cancelAlarm(Intents.ALARM.ACTION_CLOCK_RECEIVER, clock.getId());

        Ln.d("取消闹钟时间 %s ", new DateTime(clock.getAlarmMillis()).toString("yyyy-MM-dd HH:mm:ss"));
    }

    public static void plan2AlarmTimer(TimerRecord record) {
        planAlarm(Intents.ALARM.ACTION_TIMER_RECEIVER, record.getId(), record.getTime().getMillis());

        Ln.d("设置计时器响铃时间 %s ", record.getTime().toString("yyyy-MM-dd HH:mm:ss"));
    }

    public static void cancel2AlarmTimer(TimerRecord record) {
        cancelAlarm(Intents.ALARM.ACTION_TIMER_RECEIVER, record.getId());
        Ln.d("取消计时器 %s ", record.getTime().toString("yyyy-MM-dd HH:mm:ss"));
    }

    /**
     * 计算下一个闹钟的时间(如果有重复闹钟)
     *
     * @param clock 闹钟
     * @return
     */
    public static void nextAlarmClock(AlarmClock clock) {
        DateTime dateTime = new DateTime(clock.getAlarmMillis());
        //获取一个星期中的星期几 ,  星期一 : 1 , 星期二 : 2 , 如此类推 星期天 : 7 .
        int dayOfWeek = dateTime.getDayOfWeek();
        List<Integer> days = new ArrayList<Integer>(clock.getRepeat());

        //如果周期列表为空 , 或者选中的列表中包含当天 , 则认为是当天的闹钟
        if (days.isEmpty() || days.contains(dayOfWeek)) {
            //如果设置的闹钟时间是在当前时间之前的, 需要修正闹铃时间.

            if (dateTime.isBeforeNow()) {
                Period period = new Period(dateTime.withTime(0, 0, 0, 0), DateTime.now().withTime(0, 0, 0, 0));
                int intervalDays = period.toStandardDays().getDays() + 1;
                dateTime = dateTime.plusDays(intervalDays);
            }
        } else {
            //如果闹钟时间周期不包含当天

            //将当天加入到闹钟周期 , 用于获取闹钟最接近的时间 ,  假如 : 闹钟时间 : 星期四 (4), 闹钟周期 : 星期一 , 星期三 , 星期五 , 星期天 (1,3,5,7)
            // 需要得到离星期四最近的时间(即星期五) , 将当天加入到weeks (1,3,4,5,7) , 就很容易获取到 4 的下一个是 5 . 则: 闹钟从星期五开始设置.
            days.add(dayOfWeek);
            int dayIndex = days.indexOf(dayOfWeek);

            int alarmDayOfWeek = dayIndex == days.size() - 1 ? days.get(0) : days.get(dayIndex + 1);

            int needAlarmDayOfWeek = alarmDayOfWeek - dayOfWeek;
            needAlarmDayOfWeek = needAlarmDayOfWeek <= 0 ? needAlarmDayOfWeek + 7 : needAlarmDayOfWeek;

            dateTime = dateTime.plusDays(needAlarmDayOfWeek);
            days.remove((Object) dayOfWeek);
        }
        clock.setAlarmMillis(dateTime.getMillis());
        DbHelper.getInstance().getAlarmClockDao().update(clock);
        Ln.d("计算到的下一次闹钟时间 %s ", new DateTime(clock.getAlarmMillis()).toString("yyyy-MM-dd HH:mm:ss"));
    }

    public static void showIntervalTime(AlarmClock clock) {
        DateTime nowDateTime = DateTime.now();
        nowDateTime = nowDateTime.withTime(nowDateTime.getHourOfDay(), nowDateTime.getMinuteOfHour(), 0, 0);
        DateTime alarmDateTime = new DateTime(clock.getAlarmMillis());

        Period period = new Period(nowDateTime, alarmDateTime);

        if (period.getDays() > 0) {
            ToastUtil.showLongTimeMsg(String.format("此闹钟设置为%s天%s小时%s分钟后再提示!", period.getDays(), period.getHours(), period.getMinutes()));
        } else {
            ToastUtil.showLongTimeMsg(String.format("此闹钟设置为%s小时%s分钟后再提示!", period.getHours(), period.getMinutes()));
        }
    }

    private static void planAlarm(String action, int id, long millis) {
        MasterClockApplication context = MasterClockApplication.getInstance();
        Intent intent = new Intent(Intents.ALARM.ACTION_ALARM_SERVICE);
        intent.putExtra(Intents.ALARM.EXTRA_ALARM_ACTION, action);
        intent.putExtra(Intents.ALARM.EXTRA_ALARM_ID, id);
        intent.putExtra(Intents.ALARM.EXTRA_ALARM_TIME, millis);
        context.startService(intent);
    }


    private static void cancelAlarm(String action, int id) {
        MasterClockApplication context = MasterClockApplication.getInstance();
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(action);
        intent.putExtra(Intents.ALARM.EXTRA_ALARM_ID, id);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, id, intent, 0);
        alarmManager.cancel(pendingIntent);
    }
}
